package com.aqie.easy.array;

import java.util.Arrays;

/**
 * 985. 查询后的偶数和
 */
public class SumEvenAfterQueries {
    /**
     * 0 val = queries[0][0]=1  index=queries[0][1]=0   A[0] += 1
     * 1 val = queries[1][0]=-3  index=queries[1][1]=1  A[1] += -3
     *   val = X
     *   index = Y
     *  每次查询答案位 A中偶数值的和
     *  返回每次查询答案的数组
     */
    public static int[] sumEvenAfterQueries(int[] A, int[][] queries) {
        /**index + val
         * 1 + 1  6 + 2=8
         * 2+ -3  8 - 2=6
         * 2 + -4 6 + -4=2
         * 4 + 2  2 +
         */
        int length = queries.length;
        int[] ans = new int[length];
        int v1 = queries[0][0];
        int i1 = queries[0][1];

        A[i1] += v1;
        ans[0] = sumEven(A);

        for(int i = 1; i< length; i++){
            int val = queries[i][0];
            int index = queries[i][1];

            if ((isEven(A[index]) && isEven(val) )) {           // 偶偶
                ans[i] = ans[i - 1] + val;
            }else if (!isEven(A[index]) && !isEven(val)){       // 奇奇
                ans[i] = ans[i - 1] + val + A[index];
            }else if(!isEven(A[index]) && isEven(val)){         // 奇偶
                ans[i] = ans[i - 1];
            } else if((isEven(A[index]) && !isEven(val))){      // 偶
                ans[i] = ans[i - 1] - A[index];
            }
            A[index] += val;
        }
        return ans;
    }
    private static boolean isEven(int num){
        return num % 2 == 0;
    }
    private static int sumEven(int[] arr) {
        int sum = 0;
        for (int i : arr){
            if (i % 2 == 0){
                sum += i;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        // 求数组中偶数和
        int[] A = {1,2,3,4};
        int [][] queries = {{1,0},{-3,1},{-4,0},{2,3}};
        int[] ints = sumEvenAfterQueries(A, queries);
        System.out.println(Arrays.toString(ints));

        System.out.println(isEven(-1));
        System.out.println(isEven(-2));
    }


}
